import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:wan_android/model/project/project_page_model.dart';
import 'package:wan_android/model/project/tab_content_type.dart';

class ProjectPage extends StatefulWidget {
  const ProjectPage({super.key});

  @override
  State<ProjectPage> createState() => _ProjectPageState();
}

class _ProjectPageState extends State<ProjectPage> with SingleTickerProviderStateMixin {
  late TabController _tabController;

  bool visible = false;

  @override
  void initState() {
    super.initState();

    _init();
  }

  _init() async {
    final ProjectPageModel projectPageModel = Provider.of<ProjectPageModel>(context, listen: false);
    await projectPageModel.getTabBarList();

    _tabController = TabController(length: projectPageModel.tabBarList.length, vsync: this, initialIndex: 0);
    setState(() {});
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _tabController.dispose();
  }

  // 顶部切换tabs
  List<Tab> _tabs(ProjectPageModel projectPageModel) {
    return projectPageModel.tabBarList.map((item) {
      return Tab(text: item.name,);
    }).toList();
  }

  List<Widget> _tabBarViewList(ProjectPageModel projectPageModel) {
    // return projectPageModel.tabBarList.map((item) {
    //   return TabListContent(cid: item.id,);
    // }).toList();

    return List.generate(projectPageModel.tabBarList.length, (int index) => TabListContent(cid: projectPageModel.tabBarList[index].id));
  }


  // 下拉弹窗
  void _showTopModal(BuildContext context, ProjectPageModel projectPageModel) {
    showGeneralDialog(
      context: context,
      barrierDismissible: true,
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
      barrierColor: Colors.transparent,
      transitionDuration: const Duration(milliseconds: 200),
      pageBuilder: (BuildContext buildContext, Animation animation, Animation secondaryAnimation) {
        return Align(
          alignment: Alignment.topCenter,
          child: Material(
            color: Colors.transparent,
            child: Container(
              height: 300,
              width: MediaQuery.of(context).size.width,
              color: Colors.blue,
              child: ListView.builder(
                itemCount: projectPageModel.tabBarList.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(projectPageModel.tabBarList[index].name, style: TextStyle(color: _tabController.index == index ? Colors.white : Colors.black87),),
                    onTap: () {
                      Navigator.of(context).pop();
                      _tabController.index = index;
                    },
                  );
                },
              )
            ),
          ),
        );
      },
      transitionBuilder: (context, animation, secondaryAnimation, child) {
        return SlideTransition(
          position: Tween<Offset>(
            begin: const Offset(0, -1),
            end: const Offset(0, 0),
          ).animate(animation),
          child: child,
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final ProjectPageModel projectPageModel = Provider.of<ProjectPageModel>(context);
    
    if (projectPageModel.tabBarList.isEmpty) {
      return const Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    return SafeArea(
      top: false,
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.blueAccent,
          leadingWidth: 0,
          title: TabBar(
            controller: _tabController,
            isScrollable: true,
            tabAlignment: TabAlignment.start,
            onTap: (value) {
              print('点击tab');
              print(value);
            },
            tabs: _tabs(projectPageModel),
          ),
          actions: [
            IconButton(
              icon: const Icon(Icons.keyboard_arrow_down_outlined),
              onPressed: () {
                _showTopModal(context, projectPageModel);
              },
            )
          ],
        ),
        body: TabBarView(
          controller: _tabController,
          children: _tabBarViewList(projectPageModel),
        )
      ),
    );
  }
}


// tab对应的内容列表展示区
class TabListContent extends StatefulWidget {
  final int cid;
  const TabListContent({super.key, required this.cid});

  @override
  State<TabListContent> createState() => _TabListContentState();
}

class _TabListContentState extends State<TabListContent> {
  final RefreshController _refreshController = RefreshController();
  late final ProjectPageModel projectPageModel;
  int page = 1;

  List<TabContentItem> tabList = [];


  getInitialData() async {
    projectPageModel = Provider.of<ProjectPageModel>(context, listen: false);
    await projectPageModel.getTabContentList(widget.cid, page);

    setState(() {
      tabList.addAll(projectPageModel.tabContentList);
    });
  }


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getInitialData();
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: _refreshController,
      enablePullDown: true,
      enablePullUp: true,
      header: const ClassicHeader(),
      footer: const ClassicFooter(),
      onRefresh: () async {
        print('下拉刷新');
        page = 1;
        await projectPageModel.getTabContentList(widget.cid, page);
        _refreshController.refreshCompleted();
        setState(() {
          tabList = [];
          tabList.addAll(projectPageModel.tabContentList);
        });
      },
      onLoading: () async {
        // print('加载更多');
        // setState(() {
        //   page = page+1;
        // });
        page = page + 1;
        await projectPageModel.getTabContentList(widget.cid, page);
        _refreshController.loadComplete();
        setState(() {
          tabList = [...tabList, ...projectPageModel.tabContentList];
          print(tabList.length);
        });
      },
      child: SingleChildScrollView(
        child: ListView.builder(
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: tabList.length,
          itemBuilder: (BuildContext context, int index) {
            DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(tabList[index].shareDate);
            String date = '${dateTime.year}-${dateTime.month}-${dateTime.day} ${dateTime.hour}:${dateTime.minute}:${dateTime.second}';

            return InkWell(
              onTap: () {
                context.push('/webview?url=${tabList[index].link}');
              },
              child: Container(
                width: double.infinity,
                padding: EdgeInsets.symmetric(vertical: 20.h, horizontal: 40.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            const Icon(Icons.person),
                            Text(tabList[index].author),
                          ],
                        ),
                        Text(date, style: const TextStyle(fontWeight: FontWeight.bold),)
                      ]
                    ),
                    
                    Padding(
                      padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 10.w),
                      child: Text(tabList[index].title),
                    ),

                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Text(tabList[index].superChapterName.toString()),
                            Icon(Icons.circle, size: 10.sp,),
                            const Text('key: chapterName')
                            // Text(tabList[index].chapterName as String),
                          ],
                        ),
                        const Icon(Icons.favorite_border, color: Colors.redAccent,)
                      ],
                    )
                  ],
                ),
              ),
            );
          },
        )
      )
    );
  }
}
